package com.hyou.sc.common.handler.feign;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import feign.RequestInterceptor;
import feign.RequestTemplate;

/**
 * Feign层的Request拦截器处理，自定义拦截器，用于Feign层节点作负载均衡时把请求头中的内容也传递到服务节点。
 * 
 * @author FengChangshuo
 * @version 1.0.0 2018-03-30 09:18:04 初始创建
 */
public class FeignRequestInterceptor implements RequestInterceptor {
    
    @Override
    public void apply(RequestTemplate template) {
        
        RequestAttributes reqAttr = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) reqAttr;
        
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        
        if (headerNames == null) {
            return;
        }
        
        String headerName;
        String headerValue;
        while (headerNames.hasMoreElements()) {
            headerName = headerNames.nextElement();
            headerValue = request.getHeader(headerName);
            template.header(headerName, headerValue);
        }
        
    }
    
}
